<template>
  <div class="content">
    <FilterTable
      ref="packageFjxmTable"
      :height="230"
      :columns="columns"
      :dataSource="dataSource"
      :isColumnFilter="false"
      :isSelectColumn="packageType !== 'look'"
      :isToperInfo="false"
      :onCellChange="onCellChange"
      :columnsRef="$route.path + 'packageMaintenanceDLR-fjxm'"
      :onSyncTableData="onSyncTableData"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!-- <template slot="controls" slot-scope="props">
        <div style="text-align: right; margin-bottom: 10px">
          <el-button type="text" :disabled="disabledType" icon="iconfont icon-add" @click="add">新增</el-button>
          <el-button type="text" :disabled="disabledType" @click="deleteClick"><i class="el-icon-delete"></i>删除</el-button>
        </div>
      </template> -->
    </FilterTable>
    <!-- <div style="margin-top: 10px">
      <FormPanel :list="formList" :cols="8" formType="add" @formChange="changeHandle" :isSubmitBtn="false" />
    </div> -->
    <!-- <BaseDialog :visible.sync="addfjxm" title="附加项目选择" width="25%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addFjxm ref="addFjxm" @close="closeDialog" />
    </BaseDialog> -->
    <BaseDialog :visible.sync="visibleFuj" title="附加项目选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <addFuj @selectArr="selectFujFun" @closeVin="closeDialog"></addFuj>
    </BaseDialog>
  </div>
</template>

<script>
import { state, mutations } from '../store';
import addFuj from './addFuj.vue';
import { checkDiscount } from '@/utils/validate';
// import { getRepairTypeInfo } from '@/api-server/repair/repairReception/customer';

export default {
  name: 'fjxm',
  components: {
    addFuj
    // typeList
  },
  data() {
    return {
      addfjxm: false,
      visibleFuj:false,
      data: '',
      dataSource: [],
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      selectedRows: [],
      fujArr:[],
      disabledType: true,
      showTypeList: false, // 账类说明
      totalData: [], // 维修类型和账类下拉数据总和
      zlList: [
        { text: '自费', value: '3' },
        { text: '内结', value: '4' },
        { text: '保修', value: '6' },
        { text: '保险', value: '8' }
      ],
      orgList: []
    };
  },
  computed: {
    packageType() {
      return state.packageType;
    },
    packageAllMoney() {
      return state.packageAllMoney;
    },
    packageAddItemList() {
      return state.packageAddItemList;
    }
  },
  watch: {
    packageAddItemList(newVal) {
      console.log(newVal, 'packageAddItemList-watch');
      if (this.packageType !== 'add' && !this.dataSource.length) {
        this.baseTable.EXECUTE_INSERT(newVal);
      }
    }
  },
  mounted() {
    this.baseTable = this.$refs.packageFjxmTable.$refs.pageTable;
    this.getTypeData();
  },
  beforeDestroy() {},
  methods: {
    /*添加 附加 */
    selectFujFun(arr) {
      // debugger;
      this.closeDialog();

      let newArr = [];
      arr.forEach((item, index) => {
        var pos = this.fujArr.findIndex((value, index, arr) => {
          return value['addItemCode'] == item['addItemCode'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });

      this.baseTable.EXECUTE_INSERT(newArr);


    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '折扣率',
          fieldName: 'discount',
          initialValue: 1,
          placeholder: '请输入...',
          disabled: true,
          maxlength: 4,
          change: val => {
            this.handleDiscount(val);
            return;
          },
          onChange: val => {
            this.handleDiscount(val);
          },

          rules: [{ validator: checkDiscount, trigger: 'blur' }]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },

        {
          title: '项目代码',
          dataIndex: 'addItemCode'
          // sorter: true,
          // showOverflowTooltip: true
        },
        {
          title: '项目名称',
          dataIndex: 'addItemName'
          // sorter: true,
          // showOverflowTooltip: true
        },

        {
          editRequired: true,
          title: '项目费',
          dataIndex: 'addItemAmount',
          minWidth: 120,
          precision: 2,
          editable: true,
          defaultEditable: true,
          editType: 'number',
          min: 0 ,
           max:14,
          render: params => {
            return (
              <el-input
                disabled={this.packageType === 'look'}
                maxlength={8}
                min={0}
                value={params.row.addItemAmount}
                onChange={e => {
                  if(Number(e)<0){
                        this.$notify.warning({ title: '提示信息', message: '项目费不能小于0!' });
                    }
                    if(e.length>8){
                        this.$notify.warning({ title: '提示信息', message: '长度不能大于5!' });
                    }
                  params.row.addItemAmount = e;
                  this.handleJhH(params.row);
                }}
                v-model={params.row.addItemAmount}
              >

              </el-input>
            );
          }
        },

      ];
    },
    async getTypeData() {
      // const res = await getRepairTypeInfo();
      // res.data.forEach(x => {
      //   this.totalData = this.totalData.concat(x.chargePartitionVoList);
      // });
    },
    add() {
      this.visibleFuj = true;

    },
    // changeHandle(val) {},
    closeDialog(val, data) {
      console.log(data, 'closeDialog==');
      let flag = false;
      if (this.dataSource.length && data) {
        this.dataSource.forEach(x => {
          if (x.addItemCode === data.addItemCode) {
            flag = true;
          }
        });
      }
      if (flag) {
        this.$notify.warning({ title: '提示信息', message: '请勿重复添加!' });
        return;
      }
      if (data) {
        // console.log(data, '确定')
        data.discount = 1;
        // data.addItemCount = 1;
        data.accountsType = '3';
        data.rowKey = 'A';
        data.addItemAmount = data.addItemPrice;
        this.handleJhH(data);
        // if (this.dataSource.length == 0) {
        //   data['$index'] = 0;
        // }
        // this.dataSource.push(data);
        this.baseTable.EXECUTE_INSERT(data);
        this.dataSource = [...this.dataSource];
        this.$notify.success({ title: '提示信息', message: '新增成功!' });
      }
      this.visibleFuj = false;
    },
    // 行选中数据
    selectChange(val) {
      this.selectedRows = val;
    },
    // 折扣率
    handleDiscount(val) {
      const reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
      if (!reg.test(val) || !Number(val) || Number(val) > 1 || val.length > 4) {
        // console.log('handleDiscount 格式不对');
        return;
      }
      if (this.selectedRows.length) {
        this.selectedRows.forEach(item => {
          if (item.accountsType + '' === '3') {
            item.discount = val;
            item.receiveAmount = item.addItemAmount * val;
            item.discountAmount = item.addItemAmount * Number(1 - val);
          }
        });
        this.dataSource = [...this.dataSource];
      }
    },
    // 同步表格数据
    onSyncTableData(val) {
      this.fujArr = val;
      console.log(val, 'onSyncTableData------');

      let m = 0;
      let j = 0;
      for (const i of val) {

        m += i.addItemAmount ? Number(i.addItemAmount) : 0;
         j += i.manufacturerBonus ? Number(i.manufacturerBonus) : 0;

      }
      mutations.setPackageAddItemList(val);

        mutations.setAllMoney({ gs: this.packageAllMoney.gs, lj: this.packageAllMoney.lj, fj: m,fl:j,gl:this.packageAllMoney.gl,jl:this.packageAllMoney.jl });

    },
    // 监听表格数据改动
    onCellChange(change, row) {
      // 判断
      console.log(change, row, 'change,onCellChange-----');
      const key = Object.keys(change)[0];
      const name = key.substring(key.indexOf('|') + 1);


      if (name === 'addItemAmount') {
        console.log(row, 'addItemAmount---');
        this.handleJhH(row, 'addItemAmount');
      }

      this.dataSource = [...this.dataSource];
      mutations.setPackageAddItemList(this.dataSource);
      let m = 0;
      if (m !== this.packageAllMoney.fj) {
        mutations.setAllMoney({ gs: this.packageAllMoney.gs, lj: this.packageAllMoney.lj, fj: m ,jl:this.packageAllMoney.jl});

      }
    },
    handleJhH(data) {
      // type 'addItemAmount' 直接修改附加项目费
      data.addItemAmount = data.addItemAmount ? Number(data.addItemAmount).toFixed(2) : '0.00';
      data.discount = data.discount ? Number(data.discount).toFixed(2) : '1.00';
      data.manufacturerBonus = data.manufacturerBonus ? Number(data.manufacturerBonus).toFixed(2) : '0.00';
      data.afterDiscountAmount = (data.addItemAmount * data.discount).toFixed(4);
    },
    // 账类的下拉框过滤
    selectFilter(val) {
      if (val) {
        return this.totalData.filter(x => x.repairTypeCode === val);
      } else {
        return [];
      }
    },
    // 删除按钮
    deleteClick() {
      if (!this.selectedRows.length) {
        this.$notify.warning({ title: '提示信息', message: '请选择要删除的数据！' });
      } else {
        // this.$confirm('确定删除?', '提示信息', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   cancelButtonClass: 'btn-custom--cancel',
        //   type: 'warning'
        // }).then(() => {
        //   let deleteRowsArr = [];
        //   _this.selectedRows.forEach(item => {
        //     if (item.rowKey == 'A') return;
        //     item.rowKey = 'D';
        //     deleteRowsArr.push(item);
        //     // console.log(deleteRowsArr, '删除的数据')
        //   });
        // mutations.setAddItemListDelete(deleteRowsArr);
        this.baseTable.EXECUTE_DELETE(this.selectedRows);
        this.dataSource = [...this.dataSource];
        mutations.setPackageAddItemList(this.dataSource);

        // });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.content {
  // padding: 0 10px 10px 10px;
  /deep/ input::-webkit-outer-spin-button,
  /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
}
.searchBtn {
  border-radius: 0px;
}
</style>
